const express = require('express')
const app = express()
const port = 3000

//引入加密模块
const bcrypt = require('bcryptjs')


//解决跨域，引入cors
const cors = require('cors')
app.use(cors())

//引入mysql模块
const mysql = require('mysql')
//创建连接池
var db = mysql.createPool({
    connectionLimit: 10,
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'kw37'
})
// console.log(db)

//sql语句
//查询
db.query('select * from infodata', function (err, result) {
    if (err) throw err;
    console.log(result)
})



//用来解析表单form的post请求，和jq-ajax的post请求
app.use(express.urlencoded({ extended: true }))
//用来解析axios的post请求
app.use(express.json())


app.get('/', (req, res) => res.send('Hello World!'))

// 验证token
app.post('/verifyToken', (req, res) => {
    let mytoken = req.headers.token;
    if (mytoken) {
        try {
            let detoken = jwt.verify(mytoken, secret);
            console.log(detoken);
            res.send({ code: 0, msg: 'token正确' })
        } catch (error) {
            console.log(error);
            res.send({ code: 2, msg: 'token有误或过期，请重新登录' })
        }
    } else {
        res.send({ code: 1, msg: 'token不存在，请登录' })
    }

})


//注册接口
app.post('/register', (req, res) => {
    let { regname, regpass } = req.body
    // console.log(regname,regpass)
    // console.log(req.body)

    if(regname.trim() === ""){
        res.send({
            code:3,msg:'用户名不能为空'
        })
        return
    }

    //查询数据库中是否包含重复的用户名
    db.query(`SELECT username FROM infodata WHERE username=?`, [regname], (err, result) => {
        if (err) throw err;
        if (result[0]) {
            res.send({ code: 1, msg: '用户名已存在' })
        } else {
            // 插入数据
            db.query(`insert into infodata (username,password ) values(?,?)`, [regname, bcrypt.hashSync(regpass,8)], (err, result) => {
                if (err) throw err;
                console.log(result)
                res.send({ code: 0, msg: '注册成功' })
            })
        }
    })
});

// 登录接口： /login, 请求类型：post
app.post('/login', (req, res) => {
    let { logname, logpass } = req.body
    // 从数据库中查询登录用户名和登录密码是否一致
    db.query(`SELECT id,username,password FROM userinfo WHERE username=?`, [logname], (err, r) => {
        if (err) throw err;
        if (r[0]) {
            if (bcrypt.compareSync(logpass, r[0].password)) {
                // 根据登录的用户id和用户名生成token
                var token = jwt.sign({ id: r[0].id, username: r[0].username }, secret, { expiresIn: '7d' });
                // 把生成的token返回给前端
                res.send({ code: 0, msg: '登录成功', token: token, username: r[0].username })
            } else {
                res.send({ code: 2, msg: '密码错误' })
            }
        } else {
            res.send({ code: 1, msg: '用户名或密码错误！' })
        }
    });

})

app.listen(port, () => console.log(`Example app listening on port port!`))